﻿#region License

// Another free, open solution by someone who gets it.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Patterns.Reflection
{
	///<summary>
	///	Provides helper extensions for the <see cref = "MemberInfo" /> class.
	///</summary>
	public static class MemberInfoExtensions
	{
		///<summary>
		///	Gets the return type of the member info.
		///</summary>
		///<param name = "info">The member info.</param>
		///<returns>The method return type for methods, the variable type for fields and properties, and the class type for constructors.</returns>
		public static Type GetReturnType(this MemberInfo info)
		{
			return GetMethodReturnType(info as MethodBase)
			       ?? GetFieldType(info as FieldInfo)
			       ?? GetPropertyType(info as PropertyInfo);
		}

		///<summary>
		///	Gets the argument types of the member info.
		///</summary>
		///<param name = "info">The member info.</param>
		///<returns>The argument types if the member is a property with index parameters, or a constructor or method with parameters.</returns>
		///<exception cref = "NotImplementedException"></exception>
		public static IEnumerable<Type> GetArgumentTypes(this MemberInfo info)
		{
			return GetMethodArgumentTypes(info)
			       ?? GetPropertyArgumentTypes(info)
			       ?? Enumerable.Empty<Type>();
		}

		private static IEnumerable<Type> GetPropertyArgumentTypes(MemberInfo info)
		{
			throw new NotImplementedException();
		}

		private static IEnumerable<Type> GetMethodArgumentTypes(MemberInfo info)
		{
			throw new NotImplementedException();
		}

		private static Type GetMethodReturnType(MethodBase methodBase)
		{
			if (methodBase == null) return null;
			if (methodBase.IsConstructor) return methodBase.DeclaringType;
			var method = methodBase as MethodInfo;
			return method == null ? null : method.ReturnType;
		}

		private static Type GetFieldType(FieldInfo field)
		{
			return field != null ? field.FieldType : null;
		}

		private static Type GetPropertyType(PropertyInfo property)
		{
			return property != null ? property.PropertyType : null;
		}
	}
}